import React, { Component } from "react";
import { Card, Table, Button } from "antd";
import { PlusSquareTwoTone, ArrowRightOutlined } from "@ant-design/icons";
import LinkButton from "../../component/LinkButton";
import {
  reqGetCategory,
  reqChangeCategory,
  reqAddCategory,
} from "../../api/index";
import { message, Modal, Input, Form, Select } from "antd";
const { Option } = Select;
export default class Category extends Component {
  state = {
    categoryList: [],
    subCategoryList: [],
    loading: false,
    categoryTitle: "一级分类名称",
    parentId: "0",
    parentName: "",
    disabled: true,
    visible: false,
    confirmLoading: false,
    value: "",
    categoryId: "0",
    addVisible: false,
    addParentId: "0",
    addCategoryName: "",
  };
  checkChildren = async (category) => {
    await this.setState({
      parentId: category._id,
      parentName: category.name,
    });
    this.getCategory();
  };
  addhandleOk = async () => {
    if (!this.state.addCategoryName) {
      message.warning("分类名称不能为空");
      return;
    }
    const { addParentId, addCategoryName } = this.state;
    const res = await reqAddCategory(addParentId, addCategoryName);
    if (res.status !== "0") {
      message.error("分类添加失败");
      return;
    }
    message.success("分类添加成功");
    this.setState({
      addVisible: false,
      addParentId: "0",
      addCategoryName: "",
    });
    this.getCategory();
  };
  changeCategory = (category) => {
    this.showModal();
    this.setState({
      value: category.name,
      categoryId: category._id,
    });
  };
  initTopCategory = () => {
    return this.state.categoryList.map((item) => {
      return (
        <Option value={item._id} key={item._id}>
          {item.name}
        </Option>
      );
    });
  };
  initColumns = () => {
    if (this.state.parentId === "0") {
      this.columns = [
        {
          title: "分类名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "操作",
          dataIndex: "",
          key: "_id",
          width: "500px",
          render: (category) => (
            <span>
              <LinkButton
                onClick={() => {
                  this.changeCategory(category);
                }}
              >
                修改分类
              </LinkButton>
              <LinkButton
                onClick={() => {
                  this.checkChildren(category);
                }}
              >
                查看子分类
              </LinkButton>
            </span>
          ),
        },
      ];
    } else {
      this.columns = [
        {
          title: "分类名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "操作",
          dataIndex: "",
          key: "_id",
          width: "500px",
          render: (category) => (
            <span>
              <LinkButton
                onClick={() => {
                  this.changeCategory(category);
                }}
              >
                修改分类
              </LinkButton>
            </span>
          ),
        },
      ];
    }
  };
  getCategory = async () => {
    this.setState({
      loading: true,
    });

    const categoryList = await reqGetCategory(this.state.parentId);

    this.setState({
      loading: false,
    });
    if (categoryList.status !== 0) {
      message.warning("一级分类获取失败！");
    }
    if (this.state.parentId === "0") {
      this.setState({
        categoryList: categoryList.data,
      });
    } else {
      this.setState({
        subCategoryList: categoryList.data,
      });
    }
  };
  componentWillMount() {
    this.initColumns();
    this.getCategory();
  }

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = async () => {
    if (!this.state.value) {
      message.error("修改的分类名称不得为空！");
      return;
    }
    this.setState({
      confirmLoading: true,
    });
    await reqChangeCategory(this.state.categoryId, this.state.value);
    message.success("分类修改成功！");
    this.setState({
      visible: false,
      confirmLoading: false,
    });
    this.getCategory();
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      value: "this.preValue",
    });
  };

  handleInput = (e) => {
    this.preValue = this.state.value;
    // console.log(this.preValue);
    // console.log(e.target.value);
    this.setState({
      value: e.target.value,
    });
  };

  handleAdd = () => {
    this.setState({
      addVisible: true,
    });
  };
  handleAddIpt = (e) => {
    this.setState({
      addCategoryName: e.target.value,
    });
  };
  onGenderChange = (e) => {
    this.setState({
      addParentId: e,
    });
  };
  render() {
    this.initColumns();
    const {
      categoryList,
      loading,
      subCategoryList,
      parentId,
      parentName,
      visible,
      confirmLoading,

      value,
    } = this.state;
    if (parentId === "0") {
      this.whichCategory = categoryList;
    } else {
      this.whichCategory = subCategoryList;
    }

    const title =
      parentId === "0" ? (
        "一级分类名称"
      ) : (
        <span>
          <LinkButton
            onClick={() => {
              this.setState({ parentId: "0" });
              this.whichCategory = categoryList;
            }}
          >
            一级分类名称
          </LinkButton>
          <span>
            <ArrowRightOutlined style={{ marginRight: "8px" }} />
            {parentName}
          </span>
        </span>
      );

    return (
      <Card
        title={title}
        extra={
          <Button type="primary" onClick={this.handleAdd}>
            <PlusSquareTwoTone />
            <span>添加</span>
          </Button>
        }
      >
        <Modal
          title="分类名称"
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
          okText="确定"
          cancelText="取消"
        >
          <Input
            placeholder="happy everyday"
            value={value}
            onChange={this.handleInput}
          />
        </Modal>
        <Modal
          title="添加分类"
          visible={this.state.addVisible}
          onOk={this.addhandleOk}
          onCancel={() => {
            this.setState({ addVisible: false });
          }}
        >
          <Form>
            <Form.Item>
              <Select onChange={this.onGenderChange} defaultValue="一级分类">
                <Option value="一级分类" key={"0"}>
                  一级分类
                </Option>
                {this.initTopCategory()}
              </Select>
            </Form.Item>
            <Form.Item>
              <Input onChange={this.handleAddIpt} />
            </Form.Item>
          </Form>
        </Modal>
        <Table
          dataSource={this.whichCategory}
          columns={this.columns}
          bordered
          loading={loading}
          rowKey="_id"
          pagination={{
            defaultPageSize: 5,
            showQuickJumper: true,
          }}
        />
      </Card>
    );
  }
}
